<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
        <el-form-item label="姓名" prop="name">
         <el-input v-model="searchInfo.name" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
         <el-input v-model="searchInfo.idNumber" placeholder="搜索条件" :clearable="true"/>
        </el-form-item>
           <el-form-item label="上报乡镇" prop="townCode">
            <el-select v-model="searchInfo.townCode" clearable placeholder="请选择" @clear="()=>{searchInfo.townCode=undefined}">
              <el-option v-for="(item,key) in townOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
           <el-form-item label="户籍乡镇" prop="liveTownCode">
            <el-select v-model="searchInfo.liveTownCode" clearable placeholder="请选择" @clear="()=>{searchInfo.liveTownCode=undefined}">
              <el-option v-for="(item,key) in townOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="state">
            <el-select v-model="searchInfo.state" clearable placeholder="请选择" @clear="()=>{searchInfo.state=undefined}">
              <el-option v-for="(item,key) in retention_stateOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
        <el-form-item label="提交时间" prop="submitAt">
            <template #label>
            <span>
              提交时间
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
            <el-date-picker v-model="searchInfo.startSubmitAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endSubmitAt ? time.getTime() > searchInfo.endSubmitAt.getTime() : false"></el-date-picker>
            —
            <el-date-picker v-model="searchInfo.endSubmitAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startSubmitAt ? time.getTime() < searchInfo.startSubmitAt.getTime() : false"></el-date-picker>
        </el-form-item>
        <template v-if="showAllQuery">
          <el-form-item label="滞留地" prop="retention">
              <el-input v-model="searchInfo.retention" placeholder="搜索条件" />
          </el-form-item>
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="searchInfo.contactName" placeholder="搜索条件" />
          </el-form-item>
          <el-form-item label="活跃时间" prop="activateAt">
            <template #label>
            <span>
              活跃时间
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
            <el-date-picker v-model="searchInfo.startActivateAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endActivateAt ? time.getTime() > searchInfo.endActivateAt.getTime() : false"></el-date-picker>
            —
            <el-date-picker v-model="searchInfo.endActivateAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startActivateAt ? time.getTime() < searchInfo.startActivateAt.getTime() : false"></el-date-picker>
        </el-form-item>
        <el-form-item label="上报时间" prop="reportAt">
            <template #label>
            <span>
              上报时间
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
            <el-date-picker v-model="searchInfo.startReportAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endReportAt ? time.getTime() > searchInfo.endReportAt.getTime() : false"></el-date-picker>
            —
            <el-date-picker v-model="searchInfo.endReportAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startReportAt ? time.getTime() < searchInfo.startReportAt.getTime() : false"></el-date-picker>
        </el-form-item>
          <!-- 将需要控制显示状态的查询条件添加到此范围内 -->
        </template>

        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button link type="primary" icon="arrow-down" @click="showAllQuery=true" v-if="!showAllQuery">展开</el-button>
          <el-button link type="primary" icon="arrow-up" @click="showAllQuery=false" v-else>收起</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <el-button v-auth="btnAuth.add" type="primary" icon="plus" @click="openDialog()">新增</el-button>
            <el-button v-auth="btnAuth.batchDelete" icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="onDelete">删除</el-button>
            <ExportTemplate v-auth="btnAuth.exportTemplate" template-id="retention_person_CasRetentionPersons" />
            <ExportExcel v-auth="btnAuth.exportExcel" template-id="retention_person_CasRetentionPersons" />
            <ImportExcel v-auth="btnAuth.importExcel" template-id="retention_person_CasRetentionPersons" @on-success="getTableData" />
        </div>
        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="姓名" prop="name" width="80" />
        <el-table-column align="left" label="身份证号" prop="idNumber" width="180" :show-overflow-tooltip="true"/>
        <el-table-column align="left" label="年龄" prop="age" width="60"/>
        <el-table-column align="left" label="性别" prop="gender" width="60"/>
        <el-table-column align="left" label="户籍地址" prop="address" width="120" :show-overflow-tooltip="true"/>
        <el-table-column align="left" label="户籍" prop="liveTownCode" width="80" :show-overflow-tooltip="true">
            <template #default="scope">
                {{ filterDict(scope.row.liveTownCode,townOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="乡镇(上报)" prop="townCode" width="90" :show-overflow-tooltip="true">
            <template #default="scope">
                {{ filterDict(scope.row.townCode,townOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="状态" prop="state" width="100">
            <template #default="scope">
                {{ filterDict(scope.row.state,retention_stateOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="滞留地" prop="retention" width="100" />
        <el-table-column align="left" label="活跃时间" prop="activateAt" width="120">
            <template #default="scope">{{ formatDate(scope.row.activateAt) }}</template>
         </el-table-column>
          <el-table-column align="left" label="联系电话" prop="phone" width="120" />
         <el-table-column align="left" label="提交时间" prop="submitAt" width="120">
            <template #default="scope">{{ formatDate(scope.row.submitAt) }}</template>
         </el-table-column>
         <el-table-column align="left" label="上报时间" prop="reportAt" width="120">
            <template #default="scope">{{ formatDate(scope.row.reportAt) }}</template>
         </el-table-column>
        <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith">
            <template #default="scope">
            <el-button v-auth="btnAuth.info" type="primary" link class="table-button" @click="getDetails(scope.row)"><el-icon style="margin-right: 5px"><InfoFilled /></el-icon>查看</el-button>
            <el-button v-auth="btnAuth.edit" type="primary" link icon="edit" class="table-button" @click="updateCasRetentionPersonsFunc(scope.row)">编辑</el-button>
            <!-- <el-button v-auth="btnAuth.delete" type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button> -->
            <el-button type="primary" link icon="download" @click="downloadAttachments(scope.row)" v-if="scope.row.state === 'wait' || scope.row.state === 'report'">下载</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="dialogFormVisible" :show-close="false" :before-close="closeDialog">
       <template #header>
              <div class="flex justify-between items-center">
                <span class="text-lg">{{type==='create'?'新增':'编辑'}}</span>
                <div>
                  <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
                  <el-button @click="closeDialog">取 消</el-button>
                </div>
              </div>
            </template>

          <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px">
            <el-form-item label="姓名:"  prop="name" >
              <el-input v-model="formData.name" :clearable="true"  placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="头像:"  prop="avatar" v-if="type==='update'">
              <SelectImage v-model="formData.avatar" file-type="image" :type="'retention-person-detail-'+formData.ID"/>
            </el-form-item>
            <el-form-item label="身份证号:"  prop="idNumber" >
              <el-input v-model="formData.idNumber" :clearable="true"  placeholder="请输入身份证号" @change="idNumberChange"/>
            </el-form-item>
            <el-form-item label="护照号:"  prop="passportNo" >
              <el-input v-model="formData.passportNo" :clearable="true"  placeholder="请输入护照号" />
            </el-form-item>
            <el-form-item label="户籍地址:"  prop="address" >
              <el-input v-model="formData.address" :clearable="true"  placeholder="请输入户籍地址" />
            </el-form-item>
            <el-form-item label="联系电话:"  prop="phone" >
              <el-input v-model="formData.phone" :clearable="true"  placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="年龄:"  prop="age" >
              <el-input v-model.number="formData.age" :clearable="true" placeholder="请输入年龄" disabled/>
            </el-form-item>
            <el-form-item label="性别:"  prop="gender" >
              <el-input v-model="formData.gender" :clearable="true" placeholder="请输入性别" disabled/>
            </el-form-item>
            <el-form-item label="民族:"  prop="nation" > 
              <el-select v-model="formData.nation" placeholder="请选择民族" style="width:100%" :clearable="true" >
                <el-option v-for="(item,key) in nationOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="文化程度:"  prop="culture" >
              <el-select v-model="formData.culture" placeholder="请选择文化程度" style="width:100%" :clearable="true" >
                <el-option v-for="(item,key) in cultureOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="婚姻状态:"  prop="maritalStatus" >
              <el-select v-model="formData.maritalStatus" placeholder="请选择婚姻状态" style="width:100%" :clearable="true" >
                <el-option v-for="(item,key) in maritalStatusOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="滞留地:"  prop="retention" >
              <el-input v-model="formData.retention" :clearable="true"  placeholder="请输入滞留地" />
            </el-form-item>
            <el-form-item label="上报乡镇:"  prop="townCode" >
              <el-select v-model="formData.townCode" placeholder="请选择上报乡镇" style="width:100%" :clearable="true" >
                <el-option v-for="(item,key) in townOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="户籍乡镇:"  prop="liveTownCode" >
              <el-select v-model="formData.liveTownCode" placeholder="请选择户籍乡镇" style="width:100%" :clearable="true" >
                <el-option v-for="(item,key) in townOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="标签:"  prop="tag" >
              <el-input v-model="formData.tag" :clearable="true"  placeholder="请输入标签" />
            </el-form-item>
            <el-form-item label="云搜截图:"  prop="search" v-if="type==='update'">
              <SelectImage v-model="formData.search" file-type="image" :type="'retention-person-detail-'+formData.ID"/>
            </el-form-item>
            <el-form-item label="出入境截图:"  prop="entry" v-if="type==='update'">
              <SelectImage multiple :type="'retention-person-detail-'+formData.ID" v-model="formData.entry" file-type="image"/>
            </el-form-item>
            <el-form-item label="情况说明截图:"  prop="instruction" v-if="type==='update'">
              <SelectImage v-model="formData.instruction" file-type="image" :type="'retention-person-detail-'+formData.ID"/>
            </el-form-item>
            <el-form-item label="联系人:"  prop="contactName" >
              <el-input v-model="formData.contactName" :clearable="true"  placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item label="联系人电话:"  prop="contactPhone" >
              <el-input v-model="formData.contactPhone" :clearable="true"  placeholder="请输入联系人电话" />
            </el-form-item>
            <el-form-item label="状态"  prop="state" >
              <el-select v-model="formData.state" placeholder="请选择状态" style="width:100%" :clearable="true" >
                <el-option v-for="(item,key) in retention_stateOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="附件:"  prop="attachments" v-if="type==='update'">
                <SelectFile v-model="formData.attachments" :limit="99"/>
            </el-form-item>
            <el-form-item label="活跃时间:"  prop="activateAt" >
              <el-date-picker v-model="formData.activateAt" type="date" style="width:100%" placeholder="选择日期" :clearable="true"  />
            </el-form-item>
            <el-form-item label="提交时间:"  prop="submitAt" >
              <el-date-picker v-model="formData.submitAt" type="date" style="width:100%" placeholder="选择日期" :clearable="true"  />
            </el-form-item>
            <el-form-item label="上报时间:"  prop="reportAt" >
              <el-date-picker v-model="formData.reportAt" type="date" style="width:100%" placeholder="选择日期" :clearable="true"  />
            </el-form-item>
          </el-form>
    </el-drawer>

    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true" :before-close="closeDetailShow" title="查看">
            <el-descriptions :column="1" border>
                    <el-descriptions-item label="姓名">
                        {{ detailFrom.name }}
                    </el-descriptions-item>
                    <el-descriptions-item label="头像">
                      <el-image style="width: 50px; height: 50px" :preview-src-list="returnArrImg(detailFrom.avatar)" :src="getUrl(detailFrom.avatar)" fit="cover" />
                    </el-descriptions-item>
                    <el-descriptions-item label="身份证号">
                        {{ detailFrom.idNumber }}
                    </el-descriptions-item>
                    <el-descriptions-item label="护照号">
                        {{ detailFrom.passportNo }}
                    </el-descriptions-item>
                    <el-descriptions-item label="户籍地址">
                        {{ detailFrom.address }}
                    </el-descriptions-item>
                    <el-descriptions-item label="联系电话">
                        {{ detailFrom.phone }}
                    </el-descriptions-item>
                    <el-descriptions-item label="年龄">
                        {{ detailFrom.age }}
                    </el-descriptions-item>
                    <el-descriptions-item label="性别">
                      {{ detailFrom.gender }}
                    </el-descriptions-item>
                    <el-descriptions-item label="民族">
                      {{ filterDict(detailFrom.nation,nationOptions) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="文化程度">
                      {{ filterDict(detailFrom.culture,cultureOptions) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="婚姻状态">
                      {{ filterDict(detailFrom.maritalStatus,maritalStatusOptions) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="滞留地">
                        {{ detailFrom.retention }}
                    </el-descriptions-item>
                    <el-descriptions-item label="上报乡镇">
                        {{ filterDict(detailFrom.townCode,townOptions) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="户籍乡镇">
                        {{ filterDict(detailFrom.liveTownCode,townOptions) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="标签">
                        {{ detailFrom.tag }}
                    </el-descriptions-item>
                    <el-descriptions-item label="云搜截图">
                      <el-image style="width: 50px; height: 50px" :preview-src-list="returnArrImg(detailFrom.search)" :src="getUrl(detailFrom.search)" fit="cover" />
                    </el-descriptions-item>
                    <el-descriptions-item label="出入境截图">
                      <el-image style="width: 50px; height: 50px; margin-right: 10px"
                        :preview-src-list="returnArrImg(detailFrom.entry)" :initial-index="index"
                        v-for="(item,index) in detailFrom.entry" :key="index" :src="getUrl(item)" fit="cover"/>
                    </el-descriptions-item>
                    <el-descriptions-item label="情况说明">
                      <el-image style="width: 50px; height: 50px" :preview-src-list="returnArrImg(detailFrom.instruction)" :src="getUrl(detailFrom.instruction)" fit="cover" />
                    </el-descriptions-item>
                    <el-descriptions-item label="联系人">
                        {{ detailFrom.contactName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="联系人电话">
                        {{ detailFrom.contactPhone }}
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                        {{ filterDict(detailFrom.state,retention_stateOptions) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="附件">
                            <div class="fileBtn" v-for="(item,index) in detailFrom.attachments" :key="index">
                              <el-button type="primary" text bg @click="onDownloadFile(item.url)">
                                <el-icon style="margin-right: 5px"><Download /></el-icon>
                                {{item.name}}
                              </el-button>
                            </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="活跃时间">
                        {{ detailFrom.activateAt }}
                    </el-descriptions-item>
                    <el-descriptions-item label="提交时间">
                        {{ detailFrom.submitAt }}
                    </el-descriptions-item>
                    <el-descriptions-item label="上报时间">
                        {{ detailFrom.reportAt }}
                    </el-descriptions-item>
            </el-descriptions>
        </el-drawer>

  </div>
</template>

<script setup>
import {
  createCasRetentionPersons,
  deleteCasRetentionPersons,
  deleteCasRetentionPersonsByIds,
  updateCasRetentionPersons,
  findCasRetentionPersons,
  getCasRetentionPersonsList,
  generateRetentionPersonExcel
} from '@/api/retention_person/casRetentionPersons'
import { getUrl, getDownloadUrl } from '@/utils/image'
// 文件选择组件
import SelectFile from '@/components/selectFile/selectFile.vue'
import SelectImage from '@/components/selectImage/selectImage.vue'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict ,filterDataSource, returnArrImg, onDownloadFile, GetAge, GetGender} from '@/utils/format'
import { downloadZip, downloadXlsx } from '@/utils/download'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
// 引入按钮权限标识
import { useBtnAuth } from '@/utils/btnAuth'
import { useAppStore } from "@/pinia"

// 导出组件
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
// 导入组件
import ImportExcel from '@/components/exportExcel/importExcel.vue'
// 导出模板组件
import ExportTemplate from '@/components/exportExcel/exportTemplate.vue'


defineOptions({
    name: 'CasRetentionPersons'
})
// 按钮权限实例化
    const btnAuth = useBtnAuth()

// 提交按钮loading
const btnLoading = ref(false)
const appStore = useAppStore()

// 控制更多查询条件显示/隐藏状态
const showAllQuery = ref(false)

// 自动化生成的字典（可能为空）以及字段
const townOptions = ref([])
const retention_stateOptions = ref([])
const nationOptions = ref([])
const cultureOptions = ref([])
const maritalStatusOptions = ref([])
const formData = ref({
            name: '',
            avatar: '',
            idNumber: '',
            address: '',
            phone: '',
            age: undefined,
            passportNo: '',
            gender: '',
            nation: '',
            culture: '',
            maritalStatus: '',
            retention: '',
            townCode: '',
            liveTownCode: '',
            tag: '',
            search: '',
            entry: [],
            contactName: '',
            contactPhone: '',
            state: 'init',
            attachments: [],
            activateAt: undefined,
            submitAt: undefined,
            reportAt: undefined,
        })



// 验证规则
const rule = reactive({
               name : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               idNumber : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               address : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               liveTownCode : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               state : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               submitAt : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
        activateAt : [{ validator: (rule, value, callback) => {
        if (searchInfo.value.startActivateAt && !searchInfo.value.endActivateAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startActivateAt && searchInfo.value.endActivateAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startActivateAt && searchInfo.value.endActivateAt && (searchInfo.value.startActivateAt.getTime() === searchInfo.value.endActivateAt.getTime() || searchInfo.value.startActivateAt.getTime() > searchInfo.value.endActivateAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change' }],
        submitAt : [{ validator: (rule, value, callback) => {
        if (searchInfo.value.startSubmitAt && !searchInfo.value.endSubmitAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startSubmitAt && searchInfo.value.endSubmitAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startSubmitAt && searchInfo.value.endSubmitAt && (searchInfo.value.startSubmitAt.getTime() === searchInfo.value.endSubmitAt.getTime() || searchInfo.value.startSubmitAt.getTime() > searchInfo.value.endSubmitAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change' }],
        reportAt : [{ validator: (rule, value, callback) => {
        if (searchInfo.value.startReportAt && !searchInfo.value.endReportAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startReportAt && searchInfo.value.endReportAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startReportAt && searchInfo.value.endReportAt && (searchInfo.value.startReportAt.getTime() === searchInfo.value.endReportAt.getTime() || searchInfo.value.startReportAt.getTime() > searchInfo.value.endReportAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change' }],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({
  sort: 'submit_at',
  order: 'desc'
})
// 重置
const onReset = () => {
  searchInfo.value = {
    sort: 'submit_at',
    order: 'desc'
  }
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    getTableData()
  })
}

const idNumberChange = (value) => {
  formData.value.age = GetAge(value)
  formData.value.gender = GetGender(value)
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getCasRetentionPersonsList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
    townOptions.value = await getDictFunc('town')
    retention_stateOptions.value = await getDictFunc('retention_state')
    nationOptions.value = await getDictFunc('nation')
    cultureOptions.value = await getDictFunc('culture')
    maritalStatusOptions.value = await getDictFunc('marital_status')
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteCasRetentionPersonsFunc(row)
        })
    }

// 多选删除
const onDelete = async() => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
      const IDs = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          IDs.push(item.ID)
        })
      const res = await deleteCasRetentionPersonsByIds({ IDs })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        if (tableData.value.length === IDs.length && page.value > 1) {
          page.value--
        }
        getTableData()
      }
      })
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateCasRetentionPersonsFunc = async(row) => {
    const res = await findCasRetentionPersons({ ID: row.ID })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data
        dialogFormVisible.value = true
    }
}


// 删除行
const deleteCasRetentionPersonsFunc = async (row) => {
    const res = await deleteCasRetentionPersons({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// Rename this function to be more descriptive
const downloadAttachments = async (row) => {
  const res2 = await generateRetentionPersonExcel({ ID: row.ID })
  console.log(res2, 111)
  if (res2.code === 0) {
    downloadXlsx(getDownloadUrl(res2.data.filename), "滞留境外涉诈人员摸排研判信息表")
  }

  const res = await findCasRetentionPersons({ ID: row.ID })
  if (res.code === 0) {
    const filename = `${res.data.name}-${res.data.idNumber}`
    const urls = []
    res.data.attachments.forEach(attachment => {
      urls.push({
        name: attachment.name,
        url: getDownloadUrl(attachment.url)
      })
    })

    urls.push({
      name: "头像.jpg",
      url: getDownloadUrl(res.data.avatar)
    })
    urls.push({
      name: "情况说明.jpg",
      url: getDownloadUrl(res.data.instruction)
    })
    urls.push({
      name: "云搜截图.jpg",
      url: getDownloadUrl(res.data.search)
    })

    res.data.entry.forEach((item, index) => {
      urls.push({
        name: `出入境截图${index + 1}.jpg`,
        url: getDownloadUrl(item)
      })
    })

    console.log(urls)
    downloadZip(urls, filename)
  }
}

// Keep this one as is since it's for opening URLs
const downloadFile = (url) => {
    window.open(getUrl(url), '_blank')
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        name: '',
        avatar: '',
        idNumber: '',
        address: '',
        phone: '',
        age: undefined,
        nation: '',
        passportNo: '',
        culture: '',
        maritalStatus: '',
        retention: '',
        townCode: '',
        liveTownCode: '',
        tag: '',
        search: '',
        entry: [],
        contactName: '',
        contactPhone: '',
        state: 'init',
        attachments: [],
        activateAt: undefined,
        submitAt: undefined,
        reportAt: undefined,
        }
}
// 弹窗确定
const enterDialog = async () => {
     btnLoading.value = true
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return btnLoading.value = false
              let res
              switch (type.value) {
                case 'create':
                  res = await createCasRetentionPersons(formData.value)
                  break
                case 'update':
                  res = await updateCasRetentionPersons(formData.value)
                  break
                default:
                  res = await createCasRetentionPersons(formData.value)
                  break
              }
              btnLoading.value = false
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}

const detailFrom = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findCasRetentionPersons({ ID: row.ID })
  if (res.code === 0) {
    detailFrom.value = res.data
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailFrom.value = {}
}


</script>

<style>

.file-list{
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.fileBtn{
  margin-bottom: 10px;
}

.fileBtn:last-child{
  margin-bottom: 0;
}

</style>
